# -*- coding:utf-8 -*-
import pymongo
import urllib
import mongoDB
from bson.code import Code

def insertUVStat(url, imei, cnt):
    inCols = "uv_url_stat_20161220"
    inCol = mongoDB.connMongo(inCols)
    d = {}
    d['u'] = url
    d['imei'] = imei
    d['count'] = cnt
    uvStatId = inCol.insert(d)

def statUV(url, outCol):
    cols = "dmarket_access_log"
    col = mongoDB.connMongo(cols)
    mapper = Code("""function() {
        emit({imei:this.imei}, {count:1});
    }
    """)

    reducer = Code(""" function(key, values) {
        var cnt = 0;
        values.forEach(function(val) { cnt += val.count;});
        return {"count":cnt}
    }
    """)

    result = col.map_reduce(mapper, reducer, out = outCol, full_response=True, query={"u":url})
    for ret in mongoDB.connMongo(outCol).find():
        imei = ret['_id']['imei']
        cnt = ret['value']['count']
        insertUVStat(url, imei, cnt)

collections = "all_stat_20161220"
collection = mongoDB.connMongo(collections)
ret = collection.find()
uvStatCol = "uv_stat_20161220"
for item in ret:
    url = item['_id']['u']
    statUV(url, uvStatCol)
    break
    #print item['_id']['u']
    #print urllib.unquote(item['_id']['u']) + " \t " + str(item['value']['count'])

